import { UploadOutlined } from '@ant-design/icons'
import { Button, message, Upload } from 'antd'
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface'
import React, { useState } from 'react'

const UploadImg: React.FC = () => {
  const [fileList, setFileList] = useState<UploadFile[] | undefined>([])
  const handleChange: UploadProps['onChange'] = info => {
    vailImage && setFileList(info.fileList)
  }
  const CanChange = (file: RcFile | UploadFile): boolean => {
    const { type, size } = file
    const isJpgOrPng = type === 'image/jpeg' || type === 'image/png'
    if (!isJpgOrPng) {
      message.error('你只能上传 JPG/PNG 图片!')
      return false
    }
    let isLt2M
    size && (isLt2M = size / 1024 / 1024 < 4)
    if (!isLt2M) {
      message.error('图片大小不能大于4M!')
      return false
    }
    return true
  }
  const [vailImage, setVailImage] = useState(false)
  const [imageUrl, setImageUrl] = useState<string>('https://www.ttzxh.icu/api/avatar')
  const beforeUpload = (file: RcFile) => {
    const result = CanChange(file)
    setVailImage(result)
    if (result) {
      let url = window.webkitURL || window.URL
      let imgfileurl = file ? url.createObjectURL(file) : ''
      setImageUrl(imgfileurl)
    }
    return false
  }
  return (
    <Upload name="avatar" beforeUpload={beforeUpload} onChange={handleChange} maxCount={1} fileList={fileList}>
      <Button icon={<UploadOutlined />}>点击上传</Button>
      <img src={imageUrl} alt="avatar" style={{ borderRadius: '30px', margin: '0 12px' }} width="30" height="30" />
    </Upload>
  )
}

export default UploadImg
